/**
 * 53. 最大子数组和
 * https://leetcode-cn.com/problems/maximum-subarray/
 */

/**
 * @param {number[]} nums
 * @return {number}
 */
function maxSubArray(nums) {
  let pre = nums[0];
  let max = pre;
  for (let i = 1; i < nums.length; i += 1) {
    pre = Math.max(pre + nums[i], nums[i]);
    if (pre > max) {
      max = pre;
    }
  }
  return max;
}

console.log(maxSubArray([-2, 1, -3, 4, -1, 2, 1, -5, 4]) === 6);
console.log(maxSubArray([1]) === 1);
console.log(maxSubArray([5, 4, -1, 7, 8]) === 23);
